package collection;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author jiangwz
 * @create 2019/9/14.
 */
public class TestCopyOnWriteArrayList {

    static CopyOnWriteArrayList copyOnWriteArrayList = new CopyOnWriteArrayList();

    static List<String> arrayList = new ArrayList<>();

    public static void main(String[] args){
        /**
         * 有并发问题 ConcurrentModificationException
         */
//        testArrayList();

        // 无并发问题
        testCopyOnWriteArrayList();

        /**
         * 每次add元素的时候加一个ReentrantLock锁住,然后复制原来数组成为一个新的数组并扩容1个,
         * 把当前值赋予到扩容的位置
         */
//        copyOnWriteArrayList.add(UUID.randomUUID().toString().substring(0,8));
//        copyOnWriteArrayList.add(UUID.randomUUID().toString().substring(0,8));
    }

    private static void testCopyOnWriteArrayList() {
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                copyOnWriteArrayList.add(UUID.randomUUID().toString().substring(0,8));
                System.out.println(copyOnWriteArrayList);
            }, "" + i).start();
        }
    }

    /**
     *
     */
    static void testArrayList(){
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                arrayList.add(UUID.randomUUID().toString().substring(0,8));
                System.out.println(arrayList);
            }, "" + i).start();
        }
    }
}
